package com.zhenhao.xsq.netsdk_demo;
/*              Local device login process
 * 1.NetDEVSDK.NETDEV_Login() return value is glpUserID;
 * 2.if glpUserID is not equal to 0, enter live interface of NagvigationActivity;
 * */

import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog.Builder;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

import com.sdk.NETDEV_FILECOND_S;
import com.zhenhao.xsq.R;
import com.sdk.AlarmCallBack_PF;
import com.sdk.AlarmMessCallBackV30;
import com.sdk.ExceptionCallBack_PF;
import com.sdk.NETDEV_DEVICE_LOGIN_INFO_S;
import com.sdk.NETDEV_SELOG_INFO_S;
import com.sdk.NetDEVSDK;
import com.zhenhao.xsq.ui.activity.video.VideoActivity;

import java.io.Serializable;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

/*local device login*/
public class CLocalDevLogin extends Activity {

    private String TAG = "CLocalDevLogin";

    private ActionBar m_oActionBar;

    private EditText m_oUsernameTxt;
    private EditText m_oPasswordTxt;
    private EditText m_oIPTxt;
    private Button m_oLocalLoginBtn;
    private Button m_oLogoutBtn;
    private Spinner m_oLoginDeviceTypeSpin;
    private Button m_oDevDiscoveryBtn;

    static ArrayList<String> DevIpList = new ArrayList<String>();
    static ArrayList<Long> lpUserIDList = new ArrayList<Long>();
    static boolean isLoggedVMS = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.local_device_login);
        m_oActionBar = super.getActionBar();
        initActionBar();

        final NetDEVSDK oNetDemo = new NetDEVSDK();
        final AlarmCallBack_PF alarmCallback = new AlarmCallBack_PF();
        final ExceptionCallBack_PF pfExceptionCallBack = new ExceptionCallBack_PF();
        final AlarmMessCallBackV30 pfAlarmCallBackV30 = new AlarmMessCallBackV30();
        //初始化
        oNetDemo.NETDEV_Init();

        m_oLocalLoginBtn = (Button) findViewById(R.id.login);
        m_oLogoutBtn = (Button) findViewById(R.id.logout);
        m_oUsernameTxt = (EditText) findViewById(R.id.username);
        m_oPasswordTxt = (EditText) findViewById(R.id.password);
        m_oIPTxt = (EditText) findViewById(R.id.IPAddr);
        m_oLoginDeviceTypeSpin = (Spinner) findViewById(R.id.spinner_DeviceType);
        m_oDevDiscoveryBtn = (Button) findViewById(R.id.dev_discovery);


//        final Intent oIntentNagvigation = new Intent(this, CMainMenu.class);
        final Intent oIntentNagvigation = new Intent(this, VideoActivity.class);

        /*Login device , if the login is successful, start the live interface*/
        m_oLocalLoginBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {


                String strUserName = m_oUsernameTxt.getText().toString();
//				String strPassword = m_oPasswordTxt.getText().toString();
                String strPassword = "@kongchunbo0";
                String strDevIP = m_oIPTxt.getText().toString();
                if (strUserName.isEmpty() || strPassword.isEmpty()) {
                    Builder oBuilder = new Builder(CLocalDevLogin.this);
                    oBuilder.setMessage("Account or password is empty  !");
                    oBuilder.setTitle("");
                    oBuilder.setPositiveButton("OK", null);
                    oBuilder.show();
                }
                String strSelectDeviceType = m_oLoginDeviceTypeSpin.getSelectedItem().toString();
                Log.e(TAG, "strSelectDeviceType " + strSelectDeviceType);
                NETDEV_DEVICE_LOGIN_INFO_S stDevLoginInfo = new NETDEV_DEVICE_LOGIN_INFO_S();
                NETDEV_SELOG_INFO_S stSELogInfo = new NETDEV_SELOG_INFO_S();

                stDevLoginInfo.szIPAddr = strDevIP;
                stDevLoginInfo.dwPort = 80;
                stDevLoginInfo.szUserName = strUserName;
                stDevLoginInfo.szPassword = strPassword;

                if (strSelectDeviceType.equals("VMS")) {
                    NetDEVSDK.dwDeviceType = 1;
                    stDevLoginInfo.dwLoginProto = 1;
                    //stDevLoginInfo.dwDeviceType = NETDEV_DEVICE_LOGIN_INFO_S
					// .NETDEV_DEVICE_TYPE_E.NETDEV_DTYPE_VMS;
                    if (DevIpList.size() > 0) {

                        if (true == isLoggedVMS) {
                            Toast.makeText(CLocalDevLogin.this, "Login VMS allows only one!",
									Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(CLocalDevLogin.this, "Logged NVR/IPC devices, not to " +
									"be allowed to login again VMS!!", Toast.LENGTH_SHORT).show();
                        }

                        return;
                    }
                }
                if (true == isLoggedVMS) {
                    Toast.makeText(CLocalDevLogin.this, "Logged a VMS device, not to be allowed " +
							"to login again other equipment!", Toast.LENGTH_SHORT).show();
                    return;
                }
                Log.e(TAG, "NetDEVSDK.dwDeviceType " + NetDEVSDK.dwDeviceType);
                //设备登录
                NetDEVSDK.lpUserID = NetDEVSDK.NETDEV_Login_V30(stDevLoginInfo, stSELogInfo);
                Log.e(TAG, "用户ID lpUserID " + NetDEVSDK.lpUserID);
                if (0 != NetDEVSDK.lpUserID) {
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            /**
                             * 注册回调函数,接收报警消息
                             * iUserID 用户登录句柄
                             * AlarmMessCallBackV30 告警回调函数
                             * iUserData 用户数据
                             */
                            oNetDemo.NETDEV_Android_SetAlarmCallBack_V30(NetDEVSDK.lpUserID,
									pfAlarmCallBackV30, 0);
                            //注册sdk接收异常.重连等消息的回调函数
                            oNetDemo.NETDEV_Android_SetExceptionCallBack(pfExceptionCallBack, 0);
                        }
                    }).start();
                    if (!DevIpList.contains(strDevIP)) {
                        DevIpList.add(strDevIP);
                        lpUserIDList.add(NetDEVSDK.lpUserID);
                        if (strSelectDeviceType.contains("VMS")) {
                            isLoggedVMS = true;
                        }
                    }
                    oIntentNagvigation.putStringArrayListExtra("szIP", DevIpList);
                    //oIntentNagvigation.putParcelableArrayListExtra("lpUserID",lpUserIDList);
                    oIntentNagvigation.putExtra("lpUserID", (Serializable) lpUserIDList);
//					oIntentNagvigation.putStringArrayListExtra("lpUserID",()lpUserIDList);
                    oIntentNagvigation.putExtra("bLocalDevFlag", true);
                    oIntentNagvigation.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);//设置不要刷新将要跳到的界面
                    oIntentNagvigation.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    //它可以关掉所要到的界面中间的activity
                    startActivity(oIntentNagvigation);
//                    queryRecord();
                } else {
                    Builder oBuilder = new Builder(CLocalDevLogin.this);
                    oBuilder.setTitle("Fail");
                    oBuilder.setMessage("Login failed, please check if the input is correct.");
                    oBuilder.setPositiveButton("OK", null);
                    oBuilder.show();
                }
            }

        });

        /*logout device*/
        m_oLogoutBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {

                NetDEVSDK.NETDEV_Logout(NetDEVSDK.lpUserID);
                NetDEVSDK.lpUserID = 0;
                if (true == isLoggedVMS) {
                    isLoggedVMS = false;
                }
            }
        });


        final Intent intentDiscovery = new Intent(this, CDevDiscovery.class);
        m_oDevDiscoveryBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(intentDiscovery);
                finish();
            }
        });
    }

    private void initActionBar() {
        if (m_oActionBar != null) {
            //show Home
            m_oActionBar.setDisplayShowHomeEnabled(false);
            //show back button
            m_oActionBar.setDisplayHomeAsUpEnabled(true);
            m_oActionBar.setDisplayShowTitleEnabled(false);
            m_oActionBar.setHomeButtonEnabled(false);
            m_oActionBar.setDisplayUseLogoEnabled(false);
            m_oActionBar.setDisplayHomeAsUpEnabled(false);
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.

        int id = item.getItemId();
        switch (id) {
            case android.R.id.home:
                super.onBackPressed();
                break;
            default:
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    /*** return key */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {  // TODO Auto-generated method stub
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (DevIpList.isEmpty()) {
                exitBy2Click(); //exit application after double click
            } else {
                if (keyCode == KeyEvent.KEYCODE_BACK) {
                    CLocalDevLogin.this.finish();
                }
                return super.onKeyDown(keyCode, event);
            }
        }
        return false;
    }

    /**
     * function of exit after 2 click
     */
    private static Boolean isExit = false;

    private void exitBy2Click() {
        Timer tExit = null;
        if (isExit == false) {
            isExit = true;
            // prepare exiting
            Toast.makeText(this, "Press again to exit the app", Toast.LENGTH_SHORT).show();
            tExit = new Timer();
            tExit.schedule(new TimerTask() {
                @Override
                public void run() {
                    isExit = false; // cancel exit
                }
            }, 2000); // If the return key is not pressed for 2 seconds, the timer is started to cancel the task that was just executed
        } else {
            finish();

            System.exit(0);
        }
    }

    private void queryRecord() {

        int dwFileNum = 0;

        NETDEV_FILECOND_S stFileCond = new NETDEV_FILECOND_S();

        SimpleDateFormat oDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date oBeginDate = null;
        Date oEndDate = null;
        String strBeginDate = "2024-09-20";//起始年月日 "yyyy-MM-dd"
        String strBeginTime = "01:01:01";//起始时分秒 "HH:mm:ss"
        String strEndDate = "2024-09-20";//终止年月日 "yyyy-MM-dd"
        String strEndTime = "02:02:02";//终止时分秒 "HH:mm:ss"

        /*As long as the input is empty, search the video for the last 24 hours by default*/
        if (strBeginDate.equals("") || strBeginTime.equals("") || strEndDate.equals("") || strEndTime.equals("")) {
            stFileCond.dwChannelID = 2;
            stFileCond.tBeginTime = (System.currentTimeMillis() / 1000) - (60 * 60 * 24);
            //search the video for the last 24 hours by default
            stFileCond.tEndTime = System.currentTimeMillis() / 1000;
        } else {
            try {
                oBeginDate = oDateFormat.parse(strBeginDate);
            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            try {
                oEndDate = oDateFormat.parse(strEndDate);
            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            stFileCond.dwChannelID = 2;
            stFileCond.tBeginTime =
                    oBeginDate.getTime() / 1000 + Integer.parseInt(strBeginTime.substring(0, 2)) * 3600 + Integer.parseInt(strBeginTime.substring(3, 5)) * 60 + Integer.parseInt(strBeginTime.substring(6));
            stFileCond.tEndTime =
                    oEndDate.getTime() / 1000 + Integer.parseInt(strEndTime.substring(0,
                            2)) * 3600 + Integer.parseInt(strEndTime.substring(3, 5)) * 60 + Integer.parseInt(strEndTime.substring(6));
        }
        Log.e(TAG, "stFileCond isLocalDevFlag " + true);
        Log.e(TAG, "stFileCond.dwChannelID " + stFileCond.dwChannelID);
        Log.e(TAG, "stFileCond.tBeginTime " + stFileCond.tBeginTime);
        Log.e(TAG, "stFileCond.tEndTime " + stFileCond.tEndTime);
        long dwFileHandle = 0;
        if (true) {
            //根据文件类型、时间查找设备录像文件
            //dwFileHandle为录像查询业务号，返回0表示失败
            //录像查询后必须调用NETDEV_FindClose函数，防止内存泄露
            dwFileHandle = NetDEVSDK.NETDEV_FindFile(lpUserIDList.get(0), stFileCond);
        }
        Log.e(TAG, "dwFileHandle " + dwFileHandle);

        if (dwFileHandle == 0) {
//            Toast.makeText(CMainMenu.this, "Find file failed", Toast.LENGTH_SHORT).show();
//            System.out.println("find file failed");
            Log.e(TAG, "find file failed");
        } else {
            Log.e(TAG, "Find file success");
//            final NETDEV_PLAYBACKCOND_S stPlaybackInfo = new NETDEV_PLAYBACKCOND_S();//按url录像回放结构体
//            String[] szRecordFile = new String[1000];
//            NETDEV_FINDDATA_S stVodFile = new NETDEV_FINDDATA_S();//录像查找信息
//            for (int i = 0; i < 1000; i++) {
//                //逐个获取查找到的文件信息
//                int iRet = NetDEVSDK.NETDEV_FindNextFile(dwFileHandle, stVodFile);
//                if (0 == iRet) {
//                    Log.e(TAG, "find nextfile failed");
//                    break;
//                } else {
//                    dwFileNum++;
//                    NetDEVSDK.m_astVodFile[i] = new NETDEV_FINDDATA_S();
//                    NetDEVSDK.m_astVodFile[i].szFileName = stVodFile.szFileName;
//                    NetDEVSDK.m_astVodFile[i].tBeginTime = stVodFile.tBeginTime;
//                    NetDEVSDK.m_astVodFile[i].tEndTime = stVodFile.tEndTime;
//                    NetDEVSDK.m_astVodFile[i].byFileType = stVodFile.byFileType;
//                    String strBeginLocalTime, strEndLocalTime;
//                    Date nowTime = new Date(stVodFile.tBeginTime * 1000);
//                    SimpleDateFormat oBeginDateFormat = new SimpleDateFormat("yyyy.MM.dd " +
//                            "HH:mm:ss");
//                    strBeginLocalTime = oBeginDateFormat.format(nowTime);
//                    Date nowTime1 = new Date(stVodFile.tEndTime * 1000);
//                    SimpleDateFormat oEndDataFormat = new SimpleDateFormat("yyyy.MM.dd " +
//                            "HH:mm:ss");
//                    strEndLocalTime = oEndDataFormat.format(nowTime1);
//                    szRecordFile[i] = strBeginLocalTime + "---" + strEndLocalTime;
//                    Log.e(TAG, strBeginLocalTime + "---" + strEndLocalTime);
//                }
//            }
//
//            String[] szRecrodFileList;
//            if (0 == dwFileNum) {
//                szRecrodFileList = new String[1];
//                szRecrodFileList[0] = "";
//            } else {
//                szRecrodFileList = new String[dwFileNum];
//                System.arraycopy(szRecordFile, 0, szRecrodFileList, 0, dwFileNum);
//                //first by default
//                stPlaybackInfo.dwChannelID = m_stCurrentPlayInfo.dwChannelID =
//                        m_dwChannelID;
//                stPlaybackInfo.tBeginTime = m_stCurrentPlayInfo.tBeginTime =
//                        NetDEVSDK.m_astVodFile[0].tBeginTime;
//                stPlaybackInfo.tEndTime = m_stCurrentPlayInfo.tEndTime =
//                        NetDEVSDK.m_astVodFile[0].tEndTime;
//                stPlaybackInfo.dwLinkMode = m_stCurrentPlayInfo.dwLinkMode = 1;
//                m_stCurrentPlayInfo = stPlaybackInfo;
//            }
//
//            AlertDialog.Builder oBuilder = new AlertDialog.Builder(CMainMenu.this);
//            oBuilder.setTitle("Record File List");
//            oBuilder.setCancelable(false);
//            oBuilder.setSingleChoiceItems(szRecrodFileList, 0,
//                    new DialogInterface.OnClickListener() {
//                        @Override
//                        public void onClick(DialogInterface dialog, int which) {
//                            stPlaybackInfo.dwChannelID = m_dwChannelID;
//                            stPlaybackInfo.tBeginTime =
//                                    NetDEVSDK.m_astVodFile[which].tBeginTime;
//                            stPlaybackInfo.tEndTime =
//                                    NetDEVSDK.m_astVodFile[which].tEndTime;
//                            stPlaybackInfo.dwLinkMode = 1;
//                        }
//                    });
//
//            oBuilder.setPositiveButton("select", new DialogInterface.OnClickListener() {
//                public void onClick(DialogInterface dialog, int i) {
//                    m_stCurrentPlayInfo = stPlaybackInfo;
//                    dialog.dismiss();
//                }
//            });
//            oBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
//                public void onClick(DialogInterface dialog, int i) {
//                    dialog.dismiss();
//                }
//            });
//
//            oBuilder.show();
        }

        //关闭文件查找，释放资源
        int iRet = NetDEVSDK.NETDEV_FindClose(dwFileHandle);
        if (1 == iRet) {
            Log.e(TAG, "find Close success");
        } else {
            Log.e(TAG, "find Close failed");
        }
    }

}
